<?php

namespace app\admin\controller\kzvote;

use app\admin\library\Auth;
use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use think\Db;
use think\db\exception\BindParamException;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use PhpOffice\PhpSpreadsheet\IOFactory;

/**
 * 投票活动报名人员管理
 *
 * @icon fa fa-circle-o
 */
class Person extends Backend
{

    /**
     * Person模型对象
     * @var \app\common\model\kzvote\Person
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\kzvote\Person;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
        require_once ROOT_PATH . 'addons/kzvote/helper.php';

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        $vote_id = $this->request->param('vote_id','');
        $this->assignconfig('vote_id',$vote_id);
        if ($vote_id){
            $this->model->where('vote_id',$vote_id);
        }
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['vote','user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                if ($row['video']) {
                    $row['video'] = cdnurl($row['video']);
                }
                $row->getRelation('vote')->visible(['name','gift_status']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        $group = (new \app\common\model\kzvote\Vote())->order('id desc')->select();
        $this->view->assign('group',$group);

        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['vote_id'] = $params['vote_id']? $params['vote_id']:0;
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    $images          = explode(",", $params['images']);
                    $params['image'] = $images[0];
                    $params['er_code']   = '';
                    $result = $this->model->allowField(true)->save($params);
                    kzvote_qrCode($this->model, $this->model->id, 'pages/vote/person');



                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $vote_id = $this->request->param('vote_id');
        $group = (new \app\common\model\kzvote\Group)->where('vote_id',$vote_id)->order('code desc')->select();
        $groups = (new \app\common\model\kzvote\Groups)->all();
        $this->view->assign('vote_id',$vote_id);
        $this->view->assign('group',$group);
        $this->view->assign('groups',$groups);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $images          = explode(",", $params['images']);
                    $params['image'] = $images[0];

                    if($row['status'] == '10' && $params['status'] == '20'){
                        $count = $this->model
                            ->where(['vote_id' => $row['vote_id']])
                            ->where('status','20')->count();
                        $params['code'] = $count + 1;
                    }

                    $result = $row->allowField(true)->save($params);
                    if (!$row->er_code){
                        //生成小程序二维码
                        kzvote_qrCode($row, $row['id'], 'pages/vote/person');
                    }
                    Db::commit();
                } catch (ValidateException|PDOException|Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $group = (new \app\common\model\kzvote\Group)->where('vote_id',$row['vote_id'])->order('code desc')->select();
        $groups = (new \app\common\model\kzvote\Groups)->all();
        $this->view->assign('group',$group);
        $this->view->assign("row", $row);
        $this->view->assign('groups',$groups);
        return $this->view->fetch();
    }




    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['xlsx'])) {
            $this->error('请上传xlsx文件');
        }

        $reader = new Xlsx();


        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        //批量插入数据
        $this->add_all_person($insert,$this->get_excel_images($filePath));


    }

    /**
     * 批量插入
     * @param array $insert
     * @param array $images
     * @return void
     */
    public function add_all_person($insert,$images){
//                        print_r($images);exit;
        try {
            foreach ($insert as $key=> $item) {

                $item['status'] = 20;
                $item['vote_id'] = 0;
                $item['user_id'] = 1;
                $item['groups_id'] = 3;
                $item['createtime'] = time();
                $item['images']=$images[$key];
                $id = Db::table('fa_kzvote_person')->insertGetId($item);
                 kzvote_qrCode_re($id, 'pages/vote/person');
//                print_r($code);
            }

        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }

    // 获取excel表格的图片
    public function get_excel_images($file)
    {
        $imageFilePath = ROOT_PATH . 'public/uploads/images/'; //图片本地存储的路径
        if (!file_exists($imageFilePath)) { //如果目录不存在则递归创建
            mkdir($imageFilePath, 0777, true);
        }
        $datas  = [];
        try {

            $objRead = IOFactory::createReader('Xlsx');
            $objSpreadsheet = $objRead->load($file);
            $objWorksheet = $objSpreadsheet->getSheet(0);
            $data = $objWorksheet->toArray();
            foreach ($objWorksheet->getDrawingCollection() as $drawing) {
                list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());
                $imageFileName = $drawing->getCoordinates() . mt_rand(1000, 9999);
                switch ($drawing->getExtension()) {
                    case 'jpg':
                    case 'jpeg':
                        $imageFileName .= '.jpg';
                        $source = imagecreatefromjpeg($drawing->getPath());
                        imagejpeg($source, $imageFilePath . $imageFileName);
                        break;
                    case 'gif':
                        $imageFileName .= '.gif';
                        $source = imagecreatefromgif($drawing->getPath());
                        imagegif($source, $imageFilePath . $imageFileName);
                        break;
                    case 'png':
                        $imageFileName .= '.png';
                        $source = imagecreatefrompng($drawing->getPath());
                        imagepng($source, $imageFilePath . $imageFileName);
                        break;
                }
//                $data[$startRow-1][$startColumn] = '/uploads/images/' . $imageFileName;

                $datas[] = '/uploads/images/' . $imageFileName;
            }
            return $datas;
        } catch (\Exception $e) {
            throw $e;
        }
    }

    /**
     * 导出
     */
    public function export(){
        $this->relationSearch = true;

        if ($this->request->isPost()) {
            set_time_limit(0);
            $search = $this->request->post('search');
            $ids = $this->request->post('ids');
            $filter = $this->request->post('filter');
            $op = $this->request->post('op');
            $columns = $this->request->post('columns');

            $whereIds = $ids == 'all' ? '1=1' : ['person.id' => ['in', explode(',', $ids)]];
            $this->request->get(['search' => $search, 'ids' => $ids, 'filter' => json_encode($filter), 'op' => json_encode($op)]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            //设置过滤方法
            $this->request->filter(['strip_tags']);

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            //开始制作表格
            $spreadsheet = new Spreadsheet();
            $spreadsheet->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
            $spreadsheet->getDefaultStyle()->getFont()->setSize(12);
            $spreadsheet->getActiveSheet()->getColumnDimension('I')->setAutoSize(true);
            $spreadsheet->getActiveSheet()->getColumnDimension('J')->setAutoSize(true);
            $spreadsheet->getDefaultStyle()->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
            $spreadsheet->getActiveSheet()->getStyle('J')->getAlignment()->setWrapText(true);

            $worksheet = $spreadsheet->setActiveSheetIndex(0);

            $file_name = '选手导出'.date('Y-m-d H:i:s',time());

            $worksheet->getCell('A1')->setValue('序号');
            $worksheet->getCell('B1')->setValue('选手编号');
            $worksheet->getCell('C1')->setValue('选手名称');
            $worksheet->getCell('D1')->setValue('微信昵称');
            $worksheet->getCell('E1')->setValue('票数');
            $worksheet->getCell('F1')->setValue('分组名称');
            $worksheet->getCell('G1')->setValue('审核状态');
            $worksheet->getCell('H1')->setValue('报名类型');
            $worksheet->getCell('I1')->setValue('报名时间');
            $worksheet->getCell('J1')->setValue('报名选项');

            $ABC = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];

            $list = $this->model->alias('person')
                ->with(['user'])
                ->where($whereIds)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $arr = [];
            foreach ($list as $key => $val) {

                $option = '';
                if ($val['option']){
                    foreach ($val['option'][0] as $k=>$row){
                        $option .= $k.":".$row."​\n​";
                    }
                }

                $data = array($val['id'], $val['code'], $val['name'],$val['user']['nickname'],$val['count'],$val['group_name'], $val['status_text'],
                    $val['type_text'],date('Y-m-d H:i:s',$val['createtime']),$option);

                array_push($arr, $data);
            }

            foreach ($arr as $key => $row) {
                foreach ($ABC as $k => $r) {
                    $worksheet->getCell($ABC[$k] . ($key + 2))->setValue($row[$k]);
                }
            }
            $writer = IOFactory::createWriter($spreadsheet, 'Xls');
            //下载文档
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . $file_name . '.xlsx"');
            header('Cache-Control: max-age=0');
            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
            $writer->save('php://output');
        }
    }

    public function grouping()
    {

        // 获取选中的数据ID和提交的设置组ID
        $ids = $this->request->post('ids');
        $group = $this->request->post('group');
        Db::table('fa_kzvote_person')->whereIn('id',$ids)->update(['vote_id'=>$group]);
        // 响应提示
        $this->success();
    }


}
